const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const foot = require('../../templates/foot/index.js');
var cityData = require('../../utils/area.js');
var loginStatus = wx.getStorageSync("loginStatus");
const {
  $Toast
} = require('../../components/base/base');
var tabBar = foot.tabBar;
var tabBarList = [];

Page({

  data: {
    navBg: app.globalData.navBg,
    navColor: app.globalData.navColor,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    navTop: app.globalData.navHeight,
    back: false,
    navBox: false,
    tabBar: [],
    logo: 'https://chattest.metromall.cn/wfm/images/logo.png',
    store: '',
    qyopen: false, //点击门店区域筛选滑动弹窗显示效果，默认不显示
    qyshow: true, //用户点击闭关区域的弹窗设置，默认不显示
    isfull: false,
    cityleft: cityData.getCity(), //获取门店区域的下拉框筛选项内容
    citycenter: {}, //选择门店区域左边筛选框后的显示的中间内容部分
    cityright: {}, //选择门店区域的中间内容部分后显示的右边内容
    select1: '', //门店区域选中后的第二个子菜单，默认显示门店下的子菜单
    select2: '', //门店区域选择部分的中间
    select3: '', //门店区域选择部分的右边
    shownavindex: '',
    result: [],
    show: true,
    fcurNav: '',
    curNav: '',
    findex: '',
    sindex: '', //一级菜单
    curIndex: '', //二级菜单
    cateList: [],
    showSkeleton: true,
    loadMore: false,
    dcid: ''
  },

  //设置初始门店信息
  setcity: function () {
    var that = this;
    that.setData({
      select1: '上海',
      citycenter: that.data.cityleft['上海'],
      store: '上海普陀商场'
    })
  },

  // 门店区域列表下拉框是否隐藏
  listqy: function (e) {
    if (this.data.qyopen) {
      this.setData({
        qyopen: false,
        qyshow: false,
        isfull: false,
        shownavindex: 0
      })
    } else {
      this.setData({
        qyopen: true,
        qyshow: false,
        isfull: true,
        shownavindex: e.currentTarget.dataset.nav
      })
    }

  },

  // 门店区域第一栏选择内容
  selectleft: function (e) {
    this.setData({
      cityright: {},
      citycenter: this.data.cityleft[e.currentTarget.dataset.city],
      select1: e.target.dataset.city,
      select2: ''
    });
  },

  // 门店区域中间栏选择的内容
  selectcenter: function (e) {
    let leftarea = this.data.select1;
    let centerarea = this.data.select2;
    let rightarea = this.data.select3;
    if (leftarea === "" || leftarea === null || leftarea === undefined || leftarea.length === 0) {
      $Toast({
        content: "请选择省份",
        icon: 'prompt_fill',
        duration: 1
      })
    } else {
      this.setData({
        cityright: this.data.citycenter[e.currentTarget.dataset.city],
        select2: e.target.dataset.city,
        select3: ''
      });
    }

  },

  // 门店区域右边栏选择的内容
  selectright: function (e) {
    let leftarea = this.data.select1;
    let centerarea = this.data.select2;
    let rightarea = this.data.select3;
    if (leftarea === "" || leftarea === null || leftarea === undefined || leftarea.length === 0) {
      $Toast({
        content: "请选择省份",
        icon: 'prompt_fill',
        duration: 1
      })
    } else if (centerarea === "" || centerarea === null || centerarea === undefined || centerarea.length === 0) {
      $Toast({
        content: "请选择市区",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else {
      this.setData({
        select3: e.currentTarget.dataset.city
      });
    }

  },

  // 点击灰色背景隐藏所有的筛选内容
  hidebg: function (e) {

    this.setData({
      qyopen: false,
      qyshow: true,
      isfull: false,
      shownavindex: 0,
    })

  },

  // 门店区域清空筛选项
  quyuEmpty: function () {
    this.setData({
      select1: '',
      select2: '',
      select3: ''
    })
  },

  // 门店区域选择筛选项后，点击提交
  submitFilter: function () {
    let leftarea = this.data.select1;
    let centerarea = this.data.select2;
    let rightarea = this.data.select3;

    if (leftarea === "" || leftarea === null || leftarea === undefined || leftarea.length === 0) {
      $Toast({
        content: "请选择省份",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else if (centerarea === "" || centerarea === null || centerarea === undefined || centerarea.length === 0) {
      $Toast({
        content: "请选择市区",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else if (rightarea === "" || rightarea === null || rightarea === undefined || rightarea.length === 0) {
      $Toast({
        content: "请选择商场",
        icon: 'prompt_fill',
        duration: 1
      })
      return;
    } else {
      this.setData({
        qyopen: false,
        qyshow: false,
        isfull: false,
        store: this.data.select3,
        shownavindex: 0
      })
      return;
    }

  },

  search: function () {
    util.navigateTo('../search/search')
  },

  //点击最外层列表
  listTap(e) {
    var that = this;
    let Index = e.currentTarget.dataset.parentindex;
    var result = that.data.result;
    var findex = that.data.findex;
    var curNav = that.data.curNav;
    var show = that.data.show;
    //获取点击的下标值
    var navcataId = e.currentTarget.dataset.navcataid;
    result[Index].show = !result[Index].show || false;
    //变换其打开、关闭的状态
    if (result[Index].show) {
      //如果点击后是展开状态，则让其他已经展开的列表变为收起状态
      that.packUp(result, Index);
    }
    wx.showLoading({
      title: "加载中...",                             
      mask:true
    })
    that.setData({
      result: result,
      findex: Index,
      curNav: navcataId
    });

    wx.request({
      url: util.api + api.GetChannelList,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          if (res.data.MESSAGE.MESSAGE_CODE == 1) {
            for (var i = 0; i < res.data.RESULT.length; i++) {
              for (var j = 0; j < res.data.RESULT[i].NavCata.length; j++) {
                if (res.data.RESULT[i].NavCata[j]['<NavCataID>k__BackingField'] == that.data.curNav) {
                  that.setData({
                    dcid: that.data.curNav
                  })
                  wx.request({
                    url: util.api + api.ProductSecondandThreeCataList,
                    data: {
                      BUSINESS_PARAMETERS: {
                        userToekn: loginStatus.token,
                        cateId: res.data.RESULT[i].NavCata[j]['<NavCataID>k__BackingField']
                      },
                      SYSTEM_PARAMETERS: {
                        APP_ID: "M_P_G001",
                        METHOD_ID: 0,
                        ACCESS_TOKEN: "1w2Re3bE^og38",
                        TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
                        SIGN: "string"
                      }
                    },
                    method: 'POST',
                    header: {
                      'Content-Type': 'application/json'
                    },
                    success: function (obj) {
                      if (obj.statusCode == 200) {
                        if (obj.data.MESSAGE.MESSAGE_CODE == 1) {
                          that.setData({
                            cateList: obj.data.RESULT,
                            curNav: that.data.curNav
                          })
                          
                        }
                      }

                    },
                    fail: function (res) {},
                    complete: function (res) {}
                  })

                }
              }
            }
            
          }
        }

      },
      fail: function (res) {
      },
      complete: function (res) {
      }
    })

  },

  //点击里面的子列表
  listItemTap(e) {
    var that = this;
    var navcataId = e.currentTarget.dataset.navcataid;
    wx.showLoading({
      title: "加载中...",                             
      mask:true
    })
    wx.request({
      url: util.api + api.GetChannelList,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading()
        if (res.statusCode == 200) {
          if (res.data.MESSAGE.MESSAGE_CODE == 1) {
            for (var i = 0; i < res.data.RESULT.length; i++) {
              for (var j = 0; j < res.data.RESULT[i].NavCata.length; j++) {
                if (res.data.RESULT[i].NavCata[j]['<NavCataID>k__BackingField'] == navcataId) {
                  that.setData({
                    dcid: res.data.RESULT[i].NavCata[j]['<NavCataID>k__BackingField']
                  })
                  wx.request({
                    url: util.api + api.ProductSecondandThreeCataList,
                    data: {
                      BUSINESS_PARAMETERS: {
                        userToekn: loginStatus.token,
                        cateId: res.data.RESULT[i].NavCata[j]['<NavCataID>k__BackingField']
                      },
                      SYSTEM_PARAMETERS: {
                        APP_ID: "M_P_G001",
                        METHOD_ID: 0,
                        ACCESS_TOKEN: "1w2Re3bE^og38",
                        TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
                        SIGN: "string"
                      }
                    },
                    method: 'POST',
                    header: {
                      'Content-Type': 'application/json'
                    },
                    success: function (obj) {
                      if (obj.statusCode == 200) {
                        if (obj.data.MESSAGE.MESSAGE_CODE == 1) {
                          that.setData({
                            cateList: obj.data.RESULT,
                            curNav: navcataId
                          })
                          
                        }
                      }

                    },
                    fail: function (res) {
                      
                    },
                    complete: function (res) {
                    
                    }
                  })

                }
              }

            }
            
          }
        }
      },
      fail: function (res) {
        
      },
      complete: function (res) {
        
      }
    })

  },

  //所有的展开项，都变为收起
  packUp(data, index) {
    for (let i = 0, len = data.length; i < len; i++) {
      //其他最外层列表变为关闭状态
      if (index != i) {
        data[i].show = false;
      }
    }
  },

  // 左侧商品数据
  classifyLeft: function () {
    var that = this;
    var curNav = that.data.curNav;
    //一二级菜单
    wx.request({
      url: util.api + api.GetChannelList,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.MESSAGE.MESSAGE_CODE == 1) {
            res.data.RESULT[0].show = true;
            that.setData({
              result: res.data.RESULT,
              curNav: res.data.RESULT[0].NavCata[0]['<NavCataID>k__BackingField'],
              showSkeleton: false,
              dcid: res.data.RESULT[0].NavCata[0]['<NavCataID>k__BackingField']
            })
            //分类列表
            wx.request({
              url: util.api + api.ProductSecondandThreeCataList,
              data: {
                BUSINESS_PARAMETERS: {
                  userToekn: loginStatus.token,
                  cateId: that.data.curNav
                },
                SYSTEM_PARAMETERS: {
                  APP_ID: "M_P_G001",
                  METHOD_ID: 0,
                  ACCESS_TOKEN: "1w2Re3bE^og38",
                  TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
                  SIGN: "string"
                }
              },
              method: 'POST',
              header: {
                'Content-Type': 'application/json'
              },
              success: function (obj) {
                if (res.statusCode == 200) {
                  if (res.data.MESSAGE.MESSAGE_CODE == 1) {
                    var navCata = [];
                    var navCataItem = [];
                    var loadData = obj.data.RESULT;
                    // 若页面无数据
                    if (loadData == null || loadData == undefined || loadData == "" || loadData.length == 0) {
                      that.setData({
                        loadMore: true
                      })
                    } else {
                      that.setData({
                        loadMore: false
                      })
                    }
                    for (var i = 0; i < loadData.length; i++) {
                      navCata.push(loadData[i])
                    }
                    that.setData({
                      cateList: navCata,
                    })
                  }

                  if (res.data.MESSAGE.MESSAGE_CODE == 0) {
                    $Toast({
                      content: '接口异常!',
                      icon: 'prompt_fill',
                      duration: 1
                    });
                    that.setData({
                      loadMore: true
                    })
                  }
                }
              },
              fail: function (res) {
                that.setData({
                  loadMore: true
                })
              },
              complete: function (res) {}
            })
          }
        }
      },
      fail: function (res) {

      },
      complete: function (res) {

      }
    })
  },

  toTicket: function () {
    util.navigateTo('../buyticket/buyticket')
  },

  gotolist: function (e) {
    var that = this;
    var navcataId = e.currentTarget.dataset.navcataid;
    var dcid = e.currentTarget.dataset.dcid;
    util.navigateTo('../productlist/productlist?navcataid=' + navcataId + '&dcid=' + dcid)
  },

  //页面加载时购物车数量
  countCart: function (e) {
    var that = this;
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.MESSAGE.MESSAGE_CODE == 1) {
            var arr = res.data.RESULT || [];
            var counts = 0;
            //遍历购物车对其进行求和
            for (var i = 0; i < arr.length; i++) {
              counts = parseInt(counts) + parseInt(arr[i].Num);
            }
            let navCont = that.data.navCont;
            //购物车商品数量
            that.setData({
              navCont: counts
            })
          }
        }
      },
      fail: function (res) {}
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setcity();
    that.classifyLeft();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    this.countCart()
    var curNav = that.data.curNav;

    for (let i = 0; i < tabBar.length; i++) {
      tabBar[0].style = 0;
      tabBar[1].style = 1;
      tabBar[2].style = 0;
      tabBar[3].style = 0;
      tabBar[4].style = 0;
      tabBar[3].ico = 1;
      tabBarList.push(tabBar[i])
    }
    that.setData({
      tabBar: tabBarList
    })
    tabBarList.length = 0;
  },

  onReady: function () {

  }

})